﻿using System.ComponentModel;
using System.Windows.Controls;
using MaxStoreErp.Core.BaseClasses;
using MaxStoreErp.Core.Commands;
using MaxStoreErp.Core.Interfaces;
using Microsoft.Practices.Unity;

namespace MaxStoreShop.Core.EditorBase
{
    public class EditorPresenterBase<TView, TViewModel, TItemType> : PresenterBase<TView, TViewModel>
        where TView : Control, IView, new()
        where TItemType : EntityBase
        where TViewModel : EditorViewModelBase<TItemType>, new()
    {
        bool _forceExit;
        protected override void OnViewModelSet()
        {
            base.OnViewModelSet();
            ViewModel.SaveCommand = new RelayCommand(Save, CanSave);
            ViewModel.CancelCommand = new RelayCommand(OnCancelEdit);
        }

        void Save()
        {
            if (!WindowValidator.IsValid(View))
                return;

            OnSave();
        }
        protected virtual void OnSave()
        {
            
        }

        protected virtual bool CanSave()
        {
            return true;
        }

        protected virtual void OnCancelEdit()
        {
            _forceExit = true;
            Container.Resolve<IDocumentManager>().Back();
        }

        public override void OnViewClosing(CancelEventArgs eventArgs)
        {
            base.OnViewClosing(eventArgs);
            if (!ViewModel.SelectedItem.IsNew() || _forceExit)
                return;

            eventArgs.Cancel = true;
            OnClose();
        }

        async void OnClose()
        {
            var result =
                await UserMessage.QuestionMessageAsync("Вы хотите выйти без сохранения введенных в форме данных?",
                    "Подтверждение выхода");

            if (result == MessageResult.Ok)
            {
                _forceExit = true;
                Container.Resolve<IDocumentManager>().Back();
            }
        }

        protected override void OnDataLoading()
        {
            base.OnDataLoading();
            ViewModel.IsCancelVisible = ViewModel.SelectedItem.IsNew();
        }
    }
}
